;(function () {
  var assigneesConfig = {
    init:function () {
      var key = hlUrlUtil.GetQueryString('bpmKey');
      if (key == 'null') {
        $('.select-flow-name').text('合同新增').attr('data-type', 'CT')
      }
      hlSelectUi()
      var self = this;
      this.flowMesShow()
      if (key != 'null') {
        this.getFLowNodeData().done(function () {
          self.switchNav()
        })
      }
      if (key == 'null') {
        this.dom.flowNodeName([])
        this.lcDrap([{'name':'合同审批', type: 'B', userIds: [], userNames: []}])
      }
      this.adjustViewHeight()
      this.isShowMenu()
      this.switchNav()
      this.configNodeUsers()
      this.saveNodeUsers()
      this.operation()
      this.seeMore()
      this.lcSubmit()
      this.eventIsDefault()
      this.selectFlowEvent()
      this.checkAllProject()
      this.radioCheckProject()
      this.checkProject()
    },
    // 工作流程节点
    navData:[],
    index: null,
    // 工作流程处理人
    assigneesData:[],
    // 当前工作流程节点  id  name
    curFlowNode:{},
    //存储项目
    projectData: [],
    projectDataEd: [],
    //获取项目
    getprojectData: function () {
      Array.prototype.distinct = function(){
       var arr = this,
        result = [],
        i,
        j,
        len = arr.length;
       for(i = 0; i < len; i++){
        for(j = i + 1; j < len; j++){
         if(arr[i].projectId === arr[j].projectId){
          j = ++i;
         }
        }
        result.push(arr[i]);
       }
       return result;
      }
      var self = this;
      this.projectData = this.projectDataEd;
      this.selectedProject()
      hlhttp.get({
        url: 'tenant/fn_projects',
        data: {config_state: '#'},
        success: function (res) {
          var data = res.distinct();
          var str = '';
          if (data.length != self.projectDataEd.length) {
            $('.js-checkAll').removeClass('active')
          }
          data.map(function (item) {
            str += '<li class="row border-b" data-pid="'+item.projectId+'" data-name="'+item.projectName+'">\
              <div class="col-md-1">\
                <label class="ts-checkbox-label hl-icon">\
                  <input type="checkbox" name="member">\
                </label>\
              </div>\
              <div class="col-md-3 account item">'+item.areaName+'</div>\
              <div class="col-md-5 item">'+item.companyName+'</div>\
              <div class="col-md-3 pro-name item">'+item.projectName+'</div>\
            </li>';
          })
          $('.js-pro-list-container').html(str)
          $('.js-total-pro-num').text(data.length)
          var db = self.projectDataEd;
          $('.js-pro-list-container li').each(function(index, el) {
            for (var i = 0; i < db.length; i++) {
              if (db[i].projectId == $(el).attr('data-pid')) {
                $(el).find('.ts-checkbox-label').addClass('active')
              }
            }
          });
        }
      })
    },
    //全选项目
    checkAllProject: function () {
      var self = this;
      $('.js-checkAll').unbind().on('click', function () {
        var t = $(this)
        if (!t.hasClass('active')) {
          t.addClass('active')
        }
        self.projectData = [];
        $('.js-pro-list-container li').each(function(index, el) {
          var elName = $(el).attr('data-name');
          var elPid = $(el).attr('data-pid');
          if (t.hasClass('active')) {
            $(el).find('.ts-checkbox-label').addClass('active')
            self.projectData.push({name: elName, projectId: elPid})
            self.selectedProject()
          }
        });
      })
    },
    //单选项目
    checkProject: function () {
      var self = this;
      $('.js-pro-list-container').unbind().on('click', 'li .ts-checkbox-label', function(event) {
        var parent = $(this).parent().parent('li');
        if (!$(this).hasClass('active')) {
          $(this).addClass('active')
          self.projectData.push({name: parent.attr('data-name'), projectId: parent.attr('data-pid')})
          self.selectedProject()
        }
      });
    },
    //单选删除
    radioCheckProject: function () {
      var self = this;
      $('.js-selected-pro-container').unbind().on('click', 'li .js-delete-icon', function () {
        var index = $(this).parent('li').index();
        var projectId = self.projectData[index].projectId;
        self.projectData.splice(index, 1)
        var data = self.projectData;
        self.selectedProject()
        $('.js-pro-list-container li').each(function(index, el) {
          if ($(el).attr('data-pid') == projectId) {
            $(el).find('.ts-checkbox-label').removeClass('active')
          }
        });
        if (self.projectData.length != $('.js-pro-list-container li').length) {
          $('.js-checkAll').removeClass('active')
        }
      })
    },
    //已选列表
    selectedProject: function () {
      var data = this.projectData;
      if (!data.length) $('.js-selected-pro-container').html('');
      var str = '';
      data.map(function (item, index) {
        str += '<li class="row border-b" data-proid="'+item.projectId+'"><div class="col-md-2 pro-index">'+(index+1)+'</div><div class="col-md-6 pro-name pr-0" data-mes="'+item.name+'">'+item.name+'</div><div class="col-md-4 text-right js-delete-icon"><span class="hl-icon icon-Gm-delete delete-icon"></span></div></li>'
      })
      $('.js-selected-pro-container').html(str);
      $('.js-total-selected-num').text(data.length)
    },
    //适用项目
    applyProject: function () {
      var data = this.projectDataEd;
      var str = '';
      data.map(function (item, index) {
        str += '<li class="dy-flex border-b line-height-34 text-center">\
          <div class="dy-fx-1 border-r">'+(index+1)+'</div>\
          <div class="dy-fx-3 ellipsis-1">'+item.name+'</div>\
        </li>'
      })
      $('.js-apply-list').html('<li class="dy-flex border-b line-height-34 text-center"><div class="dy-fx-1 border-r">序号</div><div class="dy-fx-3">项目名称</div></li>'+str)
    },
    //选择流程
    selectFlowEvent: function () {
      var self = this;
      var bpm_key = hlUrlUtil.GetQueryString('bpmKey');
      $('.js-flow-select').unbind().on('click', 'li', function(event) {
        var is = $(this).attr('data-type')
        if (is == 'CT') {
          self.dom.flowNodeName([{name: '合同审批', type: 'B', id:0}])
          self.lcDrap([{'name':'合同审批', type: 'B', userIds: [], userNames: []}])
          $($('.assignees-nav li')[0]).find('i').trigger('click')
        }
        if (is == 'WT') {
          self.dom.flowNodeName([{name: '业务审核', type: 'B', id:0},{name: '财务审核', type: 'B',id:1}])
          self.lcDrap([{'name':'业务审核', type: 'B', userIds: [], userNames: []},{'name':'财务审核', type: 'B', userIds: [], userNames: []}])
          self.assigneesData = [{'name':'业务审核', type: 'B', userIds: [], userNames: []},{'name':'财务审核', type: 'B', userIds: [], userNames: []}]
          $($('.assignees-nav li')[0]).find('i').trigger('click')
        }

        self.projectDataEd = []
        self.applyProject()
      });
    },
    //是否默认
    eventIsDefault: function () {
      var self = this;
      $('.js-isDefault').unbind().on('click', 'li', function () {
        $(this).addClass('active').siblings('li').removeClass('active')
        var t = $(this).attr('data-type');
        if (t == 'Y') {
          $('.examine-node-item,.examine-member-item').css('width','33%')
          $('.project-item').hide()
          //清除已选列表
          self.projectDataEd = [];
          self.applyProject()
          $('.js-selected-pro-container').html('')
        }
        if (t == 'N') {
          $('.examine-node-item').css('width','20%')
          $('.examine-member-item').css({'width':'27%','overflow':'hidden'})
          $('.project-item').css({'width':'19%','border-right':'1px solid #e5e5e5'})
          $('.project-item').show()
        }
      })
      //状态选择
      $('.js-isQS').unbind().on('click', 'li', function () {
        $(this).addClass('active').siblings('li').removeClass('active')
      })
      //项目弹窗
      $('.js-show-project-set').unbind().on('click', function () {
        $('.backdrop').show()
				$('.ts-auth-project').show()
        self.getprojectData()
      })
      //关闭项目
      $('.js-close-add-pro').unbind().on('click', function () {
        $('.ts-auth-project').hide()
        $('.backdrop').hide()
        //清除已选列表
        self.projectData = [];
        self.applyProject()
        $('.js-selected-pro-container').html('')
      })
      $('.js-cancel-add-pro').unbind().on('click', function () {
        $('.ts-auth-project').hide()
        $('.backdrop').hide()
        //清除已选列表
        self.projectData = [];
        self.applyProject()
        $('.js-selected-pro-container').html('')
      })
      $('.js-ok-add-pro').unbind().on('click', function () {
        $('.ts-auth-project').hide()
        $('.backdrop').hide()
        self.projectDataEd = self.projectData;
        self.applyProject()
        self.projectData = [];
      })
    },
    // 视窗高度调整
    adjustViewHeight: function () {
      var autoMixHeight = function () {
        var viewHeight = $(window).height();  //视口高度
        var headerHeight = $('.cm-header').outerHeight(true);    // 公用头部高度
        // 确保容器的最小高度充满整个视口，若左侧菜单高于视口高度，则与左侧菜单保持同步
        var minHeight = viewHeight - headerHeight - 20
        var sideBar = $('.cm-sidebar').outerHeight()  // 左侧边栏高度
        var mainContent = minHeight < sideBar ? sideBar : minHeight // 最外层容器高度

        // $('.cm-main-content').css('min-height', mainContent)

        var flowNameContainer = $('.flow-name').outerHeight()
        var flowImageHeight = 592;

        var assignessContainer = (mainContent - flowNameContainer) > flowImageHeight ? (mainContent - flowNameContainer) : flowImageHeight
        var flowItemContainer = assignessContainer + 48

        $('.assignees-container').css('height', assignessContainer);
        $('.ass-list-project').css('height', assignessContainer);
        $('.examine-node-item').css('height', flowItemContainer);
        $('.examine-member-item').css('height', flowItemContainer);
        $('.flow-image-item').css('height', flowItemContainer);
        $('.project-item').css('height', flowItemContainer);

        // 人员审批容器离视口左侧的距离
        var left = $('.cm-main-content').offset().left + $('.cm-sidebar').outerWidth() + $('.examine-node-item').outerWidth();
        // 确保保存按钮始终在容器的最底部
        var scrollTop = $(document).scrollTop();
        var bodyHeight = $(document).height();
        if (scrollTop + viewHeight == bodyHeight) {
          $('.assignees-save').css({
            'position': 'fixed',
            'left': left,
            'bottom': '20px'
          })
        }
        if (scrollTop + viewHeight !== bodyHeight) {
          $('.assignees-save').css({
            'position': 'fixed',
            'left': left,
            'bottom': '0px'
          })
        }
      }
      autoMixHeight()
      $(window).scroll(function (event) {
        autoMixHeight()
      });
      $(window).resize(function (event) {
        autoMixHeight()
      })
    },
    // 流程名称及流程图
    flowMesShow:function () {
      // 流程名字
      var bpm_key = hlUrlUtil.GetQueryString('bpmKey');
      if(bpm_key == 'null'){
        $('.flow-name').text('合同流程');
      }
      if(bpm_key == 'CT'){
        $('.flow-name').text('合同流程');
      }
      if(bpm_key == 'WT'){
        $('.flow-name').text('退租流程');
      }
    },
    // 导航切换
    switchNav:function () {
      var self = this;
      $('.assignees-nav').unbind().on('click','li i',function (e) {
        if ($('.assignees-nav').find('input').length == 1) {
          hl.toast('请先保存')
          return
        }
        $(this).parent().addClass('active').siblings().removeClass('active');
        self.curFlowNode['name'] = $(this).text();
        self.curFlowNode['id'] = $(this).parent().attr('id');
        self.getOrganizationNodeData(0,1,$('.assignees-wrapper'),false)
      })
      $($('.assignees-nav li')[0]).find('i').trigger('click')
    },
    //操作节点
    operation: function () {
      var index = 0;
      var self = this;
      $('.flow-config-container').unbind().on('click', '.assignees-nav li span.js-bj', function(event) {
        if ($('.assignees-nav').find('input').length == 1) {
          hl.toast('请先保存')
          return
        }
        var _this = $(this).parent()
        index = _this.index()
        self.index = index;
        $($('.assignees-nav li')[index]).find('i').trigger('click')
        if (_this.attr('data-cd') == 'cs') {
          $('.js-jd-cz li').eq(2).hide()
        } else {
          $('.js-jd-cz li').eq(2).show()
        }
        var l = $(this).parent().position().left + $(this).parent().outerWidth();
        var t = $(this).parent().position().top - $('.js-jd-cz').height()/2+20;
        $('.right-pos-jd').css({left:l,top:t}).show()
        event.stopPropagation()
      });
      //确认节点
      $('.examine-node-item').on('click', 'li span.js-qr', function(event) {
        var txt = $(this).siblings('input').val();
        if (!txt) {
          hl.toast('不能为空!')
          return
        }
        var i = $(this).parent().index()
        self.index = i;
        $(this).parent().html('<i>'+txt+'</i><span class="icon-Gm-edit js-bj pull-right mr-24 js-edit-bb"></span>')
        var data = {'name':txt, type: 'P', userIds: [], userNames: []};
        self.assigneesData.splice(i,0,data)
        self.lcDrap(self.assigneesData)
        $($('.assignees-nav li')[i]).find('i').trigger('click')
        event.stopPropagation()
      });
      //编辑节点
      $('.examine-node-item').on('click', 'li span.js-ed', function(event) {
        var txt = $(this).siblings('input').val();
        var i = $(this).parent().index()
        self.index = i;
        self.assigneesData[i].name = txt;
        self.lcDrap(self.assigneesData)
        $(this).parent().html('<i>'+txt+'</i><span class="icon-Gm-edit js-bj pull-right mr-24 js-edit-bb"></span>')
        $($('.assignees-nav li')[i]).find('i').trigger('click')
        event.stopPropagation()
      });
      //删除当前input的父级 li
      $('.examine-node-item').on('click', 'li span.js-sc', function(event) {
        self.index = $(this).parent().index();
        if (self.assigneesData.length == $('.assignees-nav').children('li').length) {
          self.assigneesData.splice(self.index,1)
        }
        self.lcDrap(self.assigneesData)
        $(this).parent().remove()
        $($('.assignees-nav li')[0]).find('i').trigger('click')
        event.stopPropagation()
      });
      //操作选中节点
      $('.js-jd-cz').unbind().on('click', 'li', function(event) {
        var index1 = $(this).index()
        if (index1 == 0) {
          var str = '<li class="clearfix border-b"><input style="width:80%; height:98%; display:inline-block; outline:medium; border:0; text-indent:0.5em;" /><span class="icon-Gm-confirm js-qr pull-right js-edit-bb mr-5"></span><span class="icon-Gm-cancel js-sc pull-right mr-5 js-edit-bb"></span></li>'
          $('.assignees-nav li').eq(index).before(str)
          $('.right-pos-jd').hide()
        }
        var txt = $('.assignees-nav li').eq(index).text()
        if (index1 == 1) {
          $('.assignees-nav li').eq(index).html('<input style="width:80%; height:98%; display:inline-block; outline:medium; border:0; text-indent:0.5em; background:none;" value="'+txt+'" /><span class="icon-Gm-confirm js-ed pull-right js-edit-bb mr-5"></span><span class="icon-Gm-cancel js-sc pull-right mr-5 js-edit-bb"></span>')
          if ($('.assignees-nav li').eq(index).attr('data-cd') == 'cs') {
            $('.js-sc').hide()
          }
          $('.right-pos-jd').hide()
        }
        if (index1 == 2) {
          $('.assignees-nav li').eq(index).remove()
          self.assigneesData.splice(self.index,1)
          self.lcDrap(self.assigneesData)
          $($('.assignees-nav li')[0]).find('i').trigger('click')
          $('.right-pos-jd').hide()
        }
        event.stopPropagation()
      });
      $(document).on('click', function(event) {
        $('.right-pos-jd').hide()
        event.stopPropagation()
      });
    },
    //提交流程
    lcSubmit: function () {
      var self = this;
      var key = hlUrlUtil.GetQueryString('bpmKey');
      $('.js-lc-submit').unbind().on('click', function(event) {
        self.createFlow()
      });
    },
    //编辑
    editFlow: function () {
      var id = hlUrlUtil.GetQueryString('id');
      var self = this;
      var name = [], type = [], ids = [], names = [], flag = false;
      for (var i = 0; i < self.assigneesData.length; i++) {
        name.push(self.assigneesData[i].name)
        type.push(self.assigneesData[i].type)
        ids.push(self.assigneesData[i].userIds)
        names.push(self.assigneesData[i].userNames)
        if (self.assigneesData[i].userNames.length == 0) {
          flag = true;
        }
      }
      if (flag) {
        hl.toast('请添加配置人')
        return
      }
      var key = $('.js-lcname').attr('data-type');
      var valid;
      $('.js-isDefault li').each(function(index, el) {
        if ($(el).hasClass('active')) {
          valid = $(el).attr('data-type')
        }
      });
      var is_default;
      $('.js-isQS li').each(function(index, el) {
        if ($(el).hasClass('active')) {
          is_default = $(el).attr('data-type')
        }
      });
      var memo = $('.js-memo-flow').val()
      var project_ids = [];
      var project_names = [];
      for (var i = 0; i < self.projectDataEd.length; i++) {
        project_ids.push(self.projectDataEd[i].projectId)
        project_names.push(self.projectDataEd[i].name)
      }

      hlhttp.put({
        url: 'bpm/check_bpdef',
        data: {bpm_key:key,bpdef_id:id},
        success: function (res) {
          if (res.exist == 'Y') {
            hl.toast('此流程正在被使用不可被编辑')
            return
          }
          // var version = $('.js-version').text();
          // var flows = $('.js-lcname').text();
          // var tips = '本操作将更新'+flows+'的'+version+'版本';
          hllayer.confirm1('确认保存此流程？', function() {
            hlhttp.put({
              url: 'bpm/bpdef',
              data: {
                valid: is_default,
                memo: memo,
                project_ids: project_ids.toString() || '#',
                // project_names: project_names.toString() || '#',
                bpdef_id: id,
                phase_names: name.toString(),
                phase_types: type.toString(),
                user_ids: ids.join('#'),
                user_names: names.join('#')
              },
              success: function () {
                hl.toast('提交成功')
                hlUrlUtil.goTo('flowConfig', {ddtab:true})
              }
            })
          })
        }
      })
    },
    //创建
    createFlow: function () {
      var id = hlUrlUtil.GetQueryString('id');
      var self = this;
      var name = [], type = [], ids = [], names = [], flag = false;
      for (var i = 0; i < self.assigneesData.length; i++) {
        name.push(self.assigneesData[i].name)
        type.push(self.assigneesData[i].type)
        ids.push(self.assigneesData[i].userIds)
        names.push(self.assigneesData[i].userNames)
        if (self.assigneesData[i].userNames.length == 0) {
          flag = true;
        }
      }
      if (flag) {
        hl.toast('请添加配置人')
        return
      }
      var key = $('.select-flow-name').attr('data-type');
      var keyName = key == 'CT' ? '合同流程' : '退租流程';
      var valid;
      $('.js-isDefault li').each(function(index, el) {
        if ($(el).hasClass('active')) {
          valid = $(el).attr('data-type')
        }
      });
      var is_default;
      $('.js-isQS li').each(function(index, el) {
        if ($(el).hasClass('active')) {
          is_default = $(el).attr('data-type')
        }
      });
      var memo = $('.js-memo-flow').val()
      var project_ids = [];
      var project_names = [];
      for (var i = 0; i < self.projectDataEd.length; i++) {
        project_ids.push(self.projectDataEd[i].projectId)
        project_names.push(self.projectDataEd[i].name)
      }
      //提出一份是有点击弹框，一份没有
      function sbNx () {
        hlhttp.post({
          url: 'bpm/bpdef',
          data: {
            bpm_key: key,
            bpm_name: keyName,
            valid: is_default,
            is_default: valid,
            memo: memo,
            project_ids: project_ids.toString() || '#',
            // project_names: project_names.toString() || '#',
            // origin_bpdef_id: id,
            phase_names: name.toString(),
            phase_types: type.toString(),
            user_ids: ids.join('#'),
            user_names: names.join('#')
          },
          success: function () {
            hl.toast('提交成功')
            hlUrlUtil.goTo('flowConfig', {ddtab:true})
          }
        })
      }

      hlhttp.get({
        url: 'bpm/top_version',
        data: {bpm_key:key},
        success: function (res) {
          if (valid == 'Y') {
            if (res.topVersion) {
              var tips = '本操作将发布'+keyName+'的第'+(Number(res.topVersion)+1)+'版本，并替换第'+res.topVersion+'版本成为新的默认流程！';
              hllayer.confirm1(tips, function() {
                sbNx ()
              })
            }
            if (!res.topVersion) {
              sbNx ()
            }
          }
          if (valid == 'N') {
            sbNx ()
          }
        }
      })
    },

    // 获取工作流程节点数据
    getFLowNodeData: function () {
      var self = this;
      var dtd = $.Deferred();
      var id = hlUrlUtil.GetQueryString('id')
      hlhttp.get({
        url: 'bpm/bpdef_info',
        data: {bpdef_id: id},
        success: function (data) {
          self.assigneesData = data.bpdefPhase;
          var index = 0;
          var dealData = function (item) {
            self.navData.push({
              name: item.name,
              id: item.id,
              type: item.type
            })
            index++;
          }
          data.bpdefPhase.map(dealData)
          self.dom.flowNodeName(self.navData)
          dtd.resolve(data.bpdefPhase)
          self.lcDrap(data.bpdefPhase);
          //部分dom参数设置
          $('.js-lc-submit').text('保存流程')
          // $('.js-lcname').html(data.bpmName).attr('data-type',data.bpmKey).css('color', '#999');
          $('.js-lcname').attr('data-type',data.bpmKey)
          $('.select-flow-name').attr('data-type',data.bpmKey)
          $('.js-lcname .select-flow-name').text(data.bpmName)
          $('.js-ml-36').css('margin-left', '36px')
          // var isdefault = data.isDefault == 'Y' ? '是' : '否';
          if (data.isDefault == 'Y') {
            $('.js-isDefault li').eq(0).addClass('active').siblings('li').removeClass('active')
          }
          if (data.isDefault == 'N') {
            $('.js-isDefault li').eq(1).addClass('active').siblings('li').removeClass('active')
          }
          // var version = '<i style="margin-left:36px;"></i><b style="color:#333;width:56px;display:inline-block;">版本号</b> <b class="js-version">'+ data.version+'</b>';
          // $('.js-setAd').html(isdefault+''+version).css('color', '#999')

          if (data.valid == 'Y') {
            $('.js-isQS li').eq(0).addClass('active').siblings('li').removeClass('active')
          } else {
            $('.js-isQS li').eq(1).addClass('active').siblings('li').removeClass('active')
          }
          $('.js-memo-flow').val(data.memo)
          if (data.isDefault == 'N') {
            $('.examine-node-item').css('width','20%')
            $('.examine-member-item').css({'width':'27%','overflow':'hidden'})
            $('.project-item').css({'width':'19%','border-right':'1px solid #e5e5e5'})
            $('.project-item').show()
          }
          if (data.projectIds) {
            if (data.projectIds.length) {
              var pid = data.projectIds.split(',');
              var pname = data.projectNames.split(',');
              for (var i = 0; i < pid.length; i++) {
                self.projectDataEd.push({name:pname[i],projectId:pid[i]})
              }
              self.applyProject()
            }
          }
        }
      })
      return dtd.promise();
    },
    //流程图
    lcDrap: function (data) {
      this.assigneesData = data;
      var item = this.assigneesData;
      var str = '';
      var flag = '';
      for (var i = 0; i < this.assigneesData.length; i++) {
        // if (item[i].userNames.length < 3) {
        //   flag = 'hidden'
        // }
        // if (item[i].userNames.length > 3) {
        //   flag = ''
        // }

        str += '<li><div class="num">'+(i+1)+'</div>'
          +'<h4 class="ellipsis-1">'+item[i].name+'</h4>'
          +'<p>'+item[i].userNames.join('/')+'</p>'
        +'</li>'
      }
      $('.js-lc-pic ul').html(str)
    },
    //查看全部流程审批人
    seeMore: function () {
      var self = this;
      $('.flow-image-item').unbind().on('click', 'span', function(event) {
        var index2 = $(this).parent().index();
        $('.audit-pople-fixed h4 b').text(self.assigneesData[index2].name)
        $('.audit-pople-fixed h4 span').text(self.assigneesData[index2].userNames.length)
        $('.audit-pople-fixed .ass-list').text(self.assigneesData[index2].userNames.join('/'))
        $('.audit-pople-fixed').removeClass('hidden')
      });
      $('.js-close-ass,.js-back-ass').on('click', function(event) {
        $('.audit-pople-fixed').addClass('hidden')
      });
    },
    // 获取组织架构节点数据
    // id:父级菜单ID index:菜单级别 containerNode:菜单容器 isUsers:加载对子级菜单是否为成员 默认为false
    getOrganizationNodeData:function (id,index,containerNode,isUsers,member) {
      var self = this;
      var isUsers = isUsers || false;
      var dtd = $.Deferred();

      if(!isUsers){
        hlhttp.get({
          url: 'sub_organizations',
          data: {pid: id},
          success: function (data) {
            if(data.length){
              data.map(function (_item) {
                _item['index'] = index
              })
              self.dom.organizationNode(data,containerNode)
            }
            dtd.resolve(data);
          }
        })
      }
      if(isUsers){
        hlhttp.get({
          url: 'organization/users',
          data: {organization_id: id},
          success: function (data) {
            var newData = []
            if(data.length){
              data.map(function (_item) {
                var _obj = {};
                _obj['index'] = index;
                _obj['id'] = _item.userId
                _obj['shortName'] = _item.userName
                _obj['type'] = 'CY'
                newData.push(_obj)
              })
              self.dom.memberNode(newData,member,containerNode)
            }
            dtd.resolve(data);
          }
        })
      }
      return dtd.promise();
    },
    // 展开收缩组织架构菜单
    isShowMenu:function () {
      var self = this;
      $('.assignees-wrapper').unbind().on('click','.item',function (event) {
        if(event.target.className.indexOf('assignees-checkbox') > -1)return
        var _$this = $(this);
        var $menu = _$this;
        var arrowSign = $menu.find('.arrow-sign');  // 箭头指示图标
        var ulContainer = $menu.siblings('ul');
        var state = $menu.attr('data-state');   // 状态
        var load = $menu.data('load');  // 是否需要加载数据
        var type = $menu.data('type');  // 类型
        var id = $menu.data('id');      // 组织ID
        var index = $menu.data('index'); // 菜单级别
        var memberArr = [];    // 节点处理人

        // 节点类型为成员时不再下级数据
        if(type == 'CY')return
        // 获取当情节点流程下的节点处理人数据
        for(var i=0 ; i<self.assigneesData.length; i++){
          if(self.assigneesData[i]['name'] == self.curFlowNode.name){
            memberArr = self.assigneesData[i]['userIds']
            break;
          }
        }
        // 菜单打开关闭时更换对应状态
        // 如果没有子级菜单 则点击时不更换状态
        var updateMenuState = function () {
          if(state === 'close'){
            arrowSign.addClass('icon-GM－open').removeClass('icon-GM－stop')
            _$this.attr('data-state','open')
            ulContainer.show()
          }
          if(state === 'open'){
            arrowSign.removeClass('icon-GM－open').addClass('icon-GM－stop')
            _$this.attr('data-state','close')
            ulContainer.hide()
          }
        }

        // 如果没加载过下级数据 则加载新数据
        // 如果加载的子级菜单为成员,即父级类型为PO，则传false
        if(load === false){
          if(type == 'PO'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length)updateMenuState()
              })
          }
          if(type != 'PO'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,false)
              .done(function (data) {
                if(data.length)updateMenuState()
              })
          }
        }
      })

    },
    // 配置节点处理人
    configNodeUsers:function () {
      var self = this;
      $('.assignees-container').unbind().on('click','.assignees-checkbox',function (e) {
        var _$this = $(this);
        var $menu = _$this.parent('div');
        var ulContainer = $menu.siblings('ul');
        var state = $menu.attr('data-state');   // 状态
        var load = $menu.data('load');  // 是否需要加载数据
        var type = $menu.data('type');  // 类型
        var id = $menu.attr('data-id');      // 组织ID
        var name = _$this.siblings('.name').text(); // 节点名称
        var index = $menu.data('index'); // 菜单级别
        var dataIndex = 0;
        var checkBoxState = _$this.hasClass('active'); // true 为已选  false 为未选
        var memberArr = [];    // 节点处理人

        // 选中组织架构时则选中该组织下所有的人员
        for(var i = 0 ; i < self.assigneesData.length; i++){
          if(self.assigneesData[i]['name'] == self.curFlowNode.name){
            dataIndex = i
            memberArr = self.assigneesData[i]['userIds']
            break;
          }
        }
        var key = hlUrlUtil.GetQueryString('bpmKey');
        // if (key != 'null') return;
        // 选中的岗位 正选
        var positionMainDraw = function () {
          ulContainer.find('.assignees-checkbox').each(function () {
            if(!$(this).hasClass('active')){
              $(this).addClass('active')
              var id = $(this).parent('div').attr('data-id');
              var name = $(this).siblings('.name').text();
              self.assigneesData[dataIndex]['userIds'].push(id)
              self.assigneesData[dataIndex]['userNames'].push(name)
            }
          })
          _$this.addClass('active')
          self.lcDrap(self.assigneesData)
        }
        if(type == 'PO' && checkBoxState == false){
          if( state == 'open')positionMainDraw()
          if( state == 'close'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length == 0)return
                positionMainDraw()
              })
          }
        }

        // 选中的岗位 反选
        var positionInvert = function () {
          ulContainer.find('.assignees-checkbox').each(function () {
            var id = $(this).parent('div').attr('data-id');
            var name = $(this).siblings('.name').text();
            $(this).removeClass('active')
            self.assigneesData[dataIndex]['userNames'] = hlArrayUtil.deleteItem(self.assigneesData[dataIndex]['userNames'],name)
            self.assigneesData[dataIndex]['userIds'] = hlArrayUtil.deleteItem(self.assigneesData[dataIndex]['userIds'],id)
          })
          _$this.removeClass('active')
          self.lcDrap(self.assigneesData)
        }
        if(type == 'PO' && checkBoxState == true){
          if(state == 'open')positionInvert()
          if(state == 'close'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length == 0)return
                positionInvert()
              })
          }
        }

        // 选中的岗位下成员 正选
        // 是否全部选中，若成员全部选中，则对应上级岗位勾选
        var isAllSelected = function () {
          var $gwMenu = _$this.parent().parent().parent().siblings('div');
          var $member = _$this.parent().parent().parent().find('.assignees-checkbox');
          var flag = true;
          $member.each(function () {
            if(!$(this).hasClass('active')){
              flag = false
            }
          })
          // flag为true 选中岗位 反之不选中岗位
          if(flag){
            $gwMenu.find('.assignees-checkbox').addClass('active');
            self.lcDrap(self.assigneesData)
          }else{
            $gwMenu.find('.assignees-checkbox').removeClass('active');
            self.lcDrap(self.assigneesData)
          }
        }
        if(type == 'CY' && checkBoxState == false){
          _$this.addClass('active')
          self.assigneesData[dataIndex]['userIds'].push(id)
          self.assigneesData[dataIndex]['userNames'].push(name)
          isAllSelected()
        }

        // 选中的岗位下成员 反选
        if(type == 'CY' && checkBoxState == true){
          _$this.removeClass('active')
          self.assigneesData[dataIndex]['userNames'] = hlArrayUtil.deleteItem(self.assigneesData[dataIndex]['userNames'],name)
          self.assigneesData[dataIndex]['userIds'] = hlArrayUtil.deleteItem(self.assigneesData[dataIndex]['userIds'],id)
          isAllSelected()
        }

        e.stopPropagation();

      })
    },
    // 保存节点处理人
    saveNodeUsers:function () {
      var self = this;
      $('.assignees-save').click(function () {
        var userIdsArr = [], userNamesArr = [],bpdefPhaseId = self.curFlowNode['id'];

        for(var i = 0 ; i < self.assigneesData.length; i++){
          if(self.assigneesData[i]['name'] == self.curFlowNode.name){
            userIdsArr = self.assigneesData[i]['userIds'];
            userNamesArr = self.assigneesData[i]['userNames'];
            break;
          }
        }

        if(userIdsArr.length == 0){
          hl.toast('你还没有选中任何处理人哦')
          return
        }

        hlhttp.put({
          url:'bpdef_phase_users',
          data:{
            bpdef_phase_id:bpdefPhaseId,
            user_ids:userIdsArr.join(','),
            user_names:userNamesArr.join(',')
          },
          success:function (data) {
            hl.toast('保存成功')
          }
        })
      })
    },

    dom:{
      flowNodeName:function (data) {
        var html = '';
        var key = hlUrlUtil.GetQueryString('bpmKey');
        if (key == 'null') {
          if (!data.length) {
            data.push({name: '合同审批', type: 'B',id:0})
            assigneesConfig.assigneesData[0]={'name':'合同审批', type: 'B', userIds: [], userNames: []}
          }
        }
        data.map(function (_item) {
          html += '<li id="' + _item.id + '" data-type="'+_item.type+'" data-cd="cs" class="clearfix border-b"><i class="ellipsis-1">' + _item.name + '</i><span class="icon-Gm-edit js-bj pull-right mr-24 js-edit-bb"></span></li>'
        })
        $('.assignees-nav').html(html)
      },
      // 非成员外的组织节点
      organizationNode:function (data,containerNode) {
        var html = '';
        data.map(function (item) {
          // id  组织ID  type 组织类型  index 组织菜单级别  state 菜单状态（打开、关闭） load 点击菜单时是否需要加载新数据
          // 非岗位类型无复选框
          var checkBoxHtml = ''
          if(item.type == 'PO')checkBoxHtml = '<span class="assignees-checkbox"></span>'

          html += '<li class="cursor">'
            + '<div class="item item-' + item.index + '" data-id="' + item.id + '" data-type="' + item.type + '" data-index="' + item.index + '" data-state="close" data-load="false">'
            + '<span class="hl-icon icon-GM－stop arrow-sign"></span>'
            + checkBoxHtml
            + '<i class="name">' + item.shortName + '</i>'
            + '</div>'
            + '<ul class="container-' + item.index + '"></ul>'
          + '</li>'
        })
        containerNode.html(html)
      },
      // 成员节点
      memberNode:function (data,member,containerNode) {
        var html = '';
        var isAllSelected = true;

        if(data.length == 0)return
        data.map(function (item) {
          var isSelected = '';
          // 如果加载的组织成员在成员数组中，则选中
          for(var i = 0 ; i < member.length; i++){
            if(member[i] == item.id){
              isSelected = 'active'
              break;
            }
          }
          if(isSelected == '')isAllSelected = false

          // id  组织ID  type 组织类型  index 组织菜单级别  state 菜单状态（打开、关闭） load 点击菜单时是否需要加载新数据
          html += '<li>'
            + '<div class="member item item-' + item.index + '" data-id="' + item.id + '" data-type="' + item.type + '" data-index="' + item.index + '" data-state="close" data-load="false">'
            + '<span class="assignees-checkbox ' + isSelected + '"></span>'
            + '<i class="name">' + item.shortName + '</i>'
            + '</div>'
            + '<ul class="container-' + item.index + '"></ul>'
            + '</li>'
        })

        // 如果该岗位下所有成员被选中，则该岗位被选中
        if(isAllSelected){
          containerNode.siblings('div').find('.assignees-checkbox').addClass('active')
        }
        containerNode.html(html)
      }
    }
  }

  assigneesConfig.init()
}())
